package com.caochenlei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caochenlei.domain.Article;
import com.caochenlei.domain.ArticleVo;
import com.caochenlei.domain.Category;
import com.caochenlei.domain.Tag;
import com.caochenlei.mapper.ArticleMapper;
import com.caochenlei.mapper.CategoryMapper;
import com.caochenlei.mapper.CommentMapper;
import com.caochenlei.mapper.TagMapper;
import com.caochenlei.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
@Transactional
public class ArticleServiceImpl implements ArticleService {
    @Autowired(required = false)
    private ArticleMapper articleMapper;
    @Autowired(required = false)
    private TagMapper tagMapper;
    @Autowired(required = false)
    private CommentMapper commentMapper;
    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Override
    public ArticleVo insert(ArticleVo articleVo) {
        if (articleVo != null) {
            Article article = articleVo.getArticle();
            if (article != null) {
                log.info("插入文章：{}", article.getTitle());
                //如果摘要为空，那就设置默认摘要
                if (article.getSummary() == null || article.getSummary().equals("")) {
                    if (article.getContent() != null) {
                        if (article.getContent().length() > 64) {
                            article.setSummary(article.getContent().substring(0, 64));
                        } else {
                            article.setSummary(article.getContent());
                        }
                    }
                }
                article.setUpdateTime(new Date());
                article.setCreateTime(new Date());
                articleMapper.insert(article);
            }
            List<Tag> tags = articleVo.getTags();
            if (tags != null && tags.size() > 0) {
                for (Tag tag : tags) {
                    log.info("插入标签：{}", tag.getContent());
                    tag.setArticleId(article.getId());
                    tagMapper.insert(tag);
                }
            }

        }
        return articleVo;
    }

    @Override
    public Integer deleteById(Integer id) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", id);
        articleMapper.deleteById(id);               //删除文章信息
        tagMapper.delete(queryWrapper);             //删除文章标签
        commentMapper.delete(queryWrapper);         //删除文章评论
        return 1;
    }

    @Override
    public Integer updateById(ArticleVo articleVo) {
        if (articleVo != null && articleVo.getArticle() != null) {
            articleMapper.updateById(articleVo.getArticle());
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("article_id", articleVo.getArticle().getId());
            tagMapper.delete(queryWrapper);
        }
        if (articleVo != null && articleVo.getTags() != null) {
            for (Tag tag : articleVo.getTags()) {
                tagMapper.insert(tag);
            }
        }
        return 1;
    }

    @Override
    public ArticleVo selectById(Integer id) {
        Article article = articleMapper.selectById(id);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", id);
        List<Tag> tags = tagMapper.selectList(queryWrapper);
        ArticleVo articleVo = new ArticleVo();
        articleVo.setArticle(article);
        articleVo.setTags(tags);
        return articleVo;
    }

    @Override
    public Page<ArticleVo> search(Map<String, Object> searchMap) {
        //定义查询参数
        QueryWrapper queryWrapper = new QueryWrapper();
        Integer pageNum = 1;
        Integer pageSize = 20;
        Map<String, String> orderEntity = null;
        Map<String, String> searchEntity = null;
        //接收查询参数
        if (searchMap.get("pageNum") != null) {
            pageNum = (Integer) searchMap.get("pageNum");
        }
        if (searchMap.get("pageSize") != null) {
            pageSize = (Integer) searchMap.get("pageSize");
        }
        if (searchMap.get("orderEntity") != null) {
            orderEntity = (Map<String, String>) searchMap.get("orderEntity");
            Set<Map.Entry<String, String>> OrderEntries = orderEntity.entrySet();
            for (Map.Entry<String, String> entry : OrderEntries) {
                String orderByColumn = entry.getKey();
                String orderByValue = entry.getValue();
                if ("asc".equals(orderByValue)) {
                    queryWrapper.orderByAsc("`"+orderByColumn+"`");
                } else {
                    queryWrapper.orderByDesc("`"+orderByColumn+"`");
                }
            }
        }
        if (searchMap.get("searchEntity") != null) {
            searchEntity = (Map<String, String>) searchMap.get("searchEntity");
            //查询主键列
            if (searchEntity.get("id") != null) {
                queryWrapper.eq("id", searchEntity.get("id"));
            }
            //查询普通列
            if (searchEntity.get("summary") != null) {
                queryWrapper.like("summary", searchEntity.get("summary"));
            }
            if (searchEntity.get("read") != null) {
                queryWrapper.eq("`read`", searchEntity.get("read"));
            }
            if (searchEntity.get("is_original") != null) {
                queryWrapper.like("is_original", searchEntity.get("is_original"));
            }
            if (searchEntity.get("create_time") != null) {
                queryWrapper.like("create_time", searchEntity.get("create_time"));
            }
            if (searchEntity.get("title") != null) {
                queryWrapper.like("title", searchEntity.get("title"));
            }
            if (searchEntity.get("content") != null) {
                queryWrapper.like("content", searchEntity.get("content"));
            }
            if (searchEntity.get("is_top") != null) {
                queryWrapper.eq("is_top", searchEntity.get("is_top"));
            }
            if (searchEntity.get("cover") != null) {
                queryWrapper.like("cover", searchEntity.get("cover"));
            }
            if (searchEntity.get("update_time") != null) {
                queryWrapper.like("update_time", searchEntity.get("update_time"));
            }
            if (searchEntity.get("category_id") != null) {
                queryWrapper.like("category_id", searchEntity.get("category_id"));
            }
            if (searchEntity.get("oppose") != null) {
                queryWrapper.eq("oppose", searchEntity.get("oppose"));
            }
            if (searchEntity.get("support") != null) {
                queryWrapper.eq("support", searchEntity.get("support"));
            }
        }
        //创建分页对象
        Page<Article> page = new Page<>(pageNum, pageSize);
        //返回查询结果
        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);

        List<ArticleVo> articleVos = new ArrayList<>();
        for (Article record : articlePage.getRecords()) {
            ArticleVo articleVo = new ArticleVo();

            record.setContent(null);
            articleVo.setArticle(record);

            QueryWrapper qw1 = new QueryWrapper<>();
            qw1.eq("article_id", record.getId());
            List<Tag> tags = tagMapper.selectList(qw1);
            articleVo.setTags(tags);

            Category category = categoryMapper.selectById(record.getCategoryId());
            articleVo.setCategory(category);

            articleVos.add(articleVo);
        }

        Page<ArticleVo> articleVoPage = new Page<>();

        articleVoPage.setRecords(articleVos);
        articleVoPage.setSize(page.getSize());
        articleVoPage.setTotal(page.getTotal());
        articleVoPage.setCurrent(page.getCurrent());

        return articleVoPage;
    }

    @Override
    public Integer updateCount(Integer articleId, String filedName, Long count) {
        Article article = articleMapper.selectById(articleId);
        if (article != null) {
            if (filedName != null && filedName.equals("read")) article.setRead(article.getRead() + count);
            if (filedName != null && filedName.equals("support")) article.setSupport(article.getSupport() + count);
            if (filedName != null && filedName.equals("oppose")) article.setOppose(article.getOppose() + count);
            articleMapper.updateById(article);
            return 1;
        } else {
            return 0;
        }
    }
}
